#include <string.h>
#include "esp_log.h"

#include "esp_partition.h"
#include "sgf_cfg.h"



sgf_cfg_t sgf_cfg;

const esp_partition_t *data_partition = NULL;
static const char* TAG = "cfg";
#define  MAGIC_NUM 0xAABBCCDD

int sgf_cfg_write(sgf_cfg_t *cfg)
{
    cfg->magic = MAGIC_NUM;
    uint8_t *buf = (uint8_t *)cfg;
    ESP_LOGI(TAG, "write cfg");
    if (esp_partition_erase_range(data_partition, 0, data_partition->size) != ESP_OK) {
        ESP_LOGI(TAG, "erase cfg failed");
        return -1;
    }
    esp_partition_write(data_partition, 0, buf, sizeof(sgf_cfg_t));
    return 0;
}

int sgf_cfg_read(sgf_cfg_t *cfg)
{
    uint8_t *buf = (uint8_t *)cfg;
    ESP_LOGI(TAG, "read cfg");
    if (esp_partition_read(data_partition, 0, buf, sizeof(sgf_cfg_t)) != ESP_OK) {
        ESP_LOGI(TAG, "read cfg failed");
        return -1;
    }
    
    return 0;
}


int sgf_cfg_init(void)
{
    data_partition = esp_partition_find_first(0x50, 0x00, "sgf");
    if (data_partition != NULL) {
        ESP_LOGI(TAG, "partiton addr: 0x%08x; size: %d; label: %s\n", data_partition->address, data_partition->size, data_partition->label);
    } else {
        ESP_LOGE(TAG, "Partition error: can't find partition name: %s\n", "sgf");
        return -1;
    }
    sgf_cfg_read(&sgf_cfg);
    if (sgf_cfg.magic == MAGIC_NUM) {
        ESP_LOGI(TAG, "cfg success");
        return 0;
    }
    ESP_LOGI(TAG, "cfg is null, magic=%x", sgf_cfg.magic);
    memset(&sgf_cfg, 0, sizeof(sgf_cfg_t));
    return -1;
}

int sgf_cfg_reset(void)
{
    memset(&sgf_cfg, 0, sizeof(sgf_cfg_t));
    uint8_t *buf = (uint8_t *)&sgf_cfg;
    ESP_LOGI(TAG, "reset cfg");
    if (esp_partition_erase_range(data_partition, 0, data_partition->size) != ESP_OK) {
        ESP_LOGI(TAG, "erase cfg failed");
        return -1;
    }
    esp_partition_write(data_partition, 0, buf, sizeof(sgf_cfg_t));
    return 0;
}

char *sgf_get_http_code(void)
{
    return sgf_cfg.http.code;
}

char *sgf_get_http_key(void)
{
    return sgf_cfg.http.key;
}

char *sgf_get_gui_remind(void)
{
    return sgf_cfg.gui.remind;
}
char *sgf_get_wifi_passwd(void)
{
    return sgf_cfg.wifi.passwd;
}
char *sgf_get_wifi_ssid(void)
{
    return sgf_cfg.wifi.ssid;
}